package com.woniuxy.vuecli.controller;

import com.woniuxy.vuecli.entity.Employee;
import com.woniuxy.vuecli.entity.EmployeeRemoveDTO;
import com.woniuxy.vuecli.entity.PageBean;
import com.woniuxy.vuecli.entity.ResponseResult;
import com.woniuxy.vuecli.exception.VeriyCodeException;
import com.woniuxy.vuecli.service.EmployeeService;
import com.woniuxy.vuecli.util.JwtUtil;
import com.woniuxy.vuecli.validategroup.EmployeeAddValidate;
import com.woniuxy.vuecli.validategroup.EmployeeModifyValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Author author
 * @Create 2024-01-15 10:09
 */
//@CrossOrigin
@Slf4j    //自动创建日志核心类的对象
@RequestMapping("/employee")
@RestController
public class EmployeeController {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    EmployeeService employeeService;

    //SpringMVC支持路径变量传参
    //@RequestBody Employee employee
    //{eid:1,ename:zs}
    @RequestMapping("/getAll/{pageIndex}/{pageSize}")
    public ResponseResult<PageBean<Employee>> getAll(
            @PathVariable("pageIndex") int pageIndex,
            @PathVariable("pageSize") int pageSize,
            @RequestBody Employee employee) {
        PageBean<Employee> pageBean = employeeService.getAll(pageIndex, pageSize, employee);
        return new ResponseResult<>(200, "ok", pageBean);
    }

    @RequestMapping("/getByEmail/{email}")
    public ResponseResult<Boolean> getByEmail(@PathVariable("email") String email) {
        return new ResponseResult<>(200, "ok", employeeService.emailUsed(email));
    }

    //(@Valid对象的属性使用级联验证。BindingResult，spring封装的类，用来保存验证信息)
    @RequestMapping("/add")
    public ResponseResult add(@Validated(EmployeeAddValidate.class) @RequestBody Employee employee/*, BindingResult bindingResult*/) {
        log.info("employee={}", employee);
        //执行添加操作
        employeeService.add(employee);
        return new ResponseResult(200, "ok", null);
    }

    @RequestMapping("/modify")
    public ResponseResult modify(@Validated(EmployeeModifyValidate.class) @RequestBody Employee employee/*, BindingResult bindingResult*/) {


        //执行修改操作
        return new ResponseResult(200, "ok", null);
    }

    @RequestMapping("/test")
    public ResponseResult test() {

        if (true) {
            throw new RuntimeException("ex");
        }
        return new ResponseResult(200, "ok", "test-ok");

    }

    @RequestMapping("/remove/{eid}")
    public ResponseResult remove(@PathVariable("eid")int eid) {
        log.info("remove={}", eid);
        //执行逻辑删除操作
        return new ResponseResult(200, "ok", null);
    }

    @RequestMapping("/removeBatch")
    public ResponseResult removeBatch(@RequestBody EmployeeRemoveDTO employeeRemoveDTO) {
        log.info("eids={}", employeeRemoveDTO.getEids());
        //执行逻辑删除操作
        return new ResponseResult(200, "ok", null);
    }
    @RequestMapping("/login")
    public ResponseResult login(String ename, String password,String verifycodeid,String verifycode, HttpServletResponse response) {
//        log.info("verifycodeid={}", verifycodeid);
//        log.info("验证码校验输入={},redis={}", verifycode,redisTemplate.opsForValue().get(verifycodeid));
//        log.info("验证码校验比较={}}", verifycode.equals(redisTemplate.opsForValue().get(verifycodeid)));
        //验证码校验
        if(!verifycode.equals(redisTemplate.opsForValue().get(verifycodeid))){
            //验证码错误，抛异常
            throw new VeriyCodeException("验证码错误");
        }else{
            //验证通过，删除key
            redisTemplate.delete(verifycodeid);
        }

        //登录验证
        Employee employee = employeeService.login(ename, password);
        //验证成功，生成token
        String token = JwtUtil.create(employee.getEid().toString(), employee.getEname());
//        String refreshtoken = JwtUtil.createfresh(employee.getEid().toString(), employee.getEname());
        //token存入响应头
        response.setHeader("token", token);
        //token存入Redis，Redis设置2倍的过期时间
        redisTemplate.opsForValue().set("token:"+token, "xxxx", 20, TimeUnit.SECONDS);
//        response.setHeader("refreshtoken", refreshtoken);
//        //前后端分离，跨域，后端必须暴露响应头，否则前端无法获取
        //请求头，响应头，请求参数，Cookie,Session都是key-value,下面的写法，前端只会收到refreshtoken
//        response.setHeader("Access-Control-Expose-Headers", "token");
//        response.setHeader("Access-Control-Expose-Headers", "refreshtoken");
        //多个响应头使用逗号分隔
//        response.setHeader("Access-Control-Expose-Headers", "token,refreshtoken");
        response.setHeader("Access-Control-Expose-Headers", "*");
        return new ResponseResult(200, "ok", null);
    }

}
